unit frmMain;

{$mode Delphi} {$H+}
{$modeswitch functionreferences}{$modeswitch anonymousfunctions}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
  hmglobals, hmaibote;

type

  { TFormMain }

  TFormMain = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Memo1:   TMemo;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private

  public
    procedure log(const msg: string);
  end;

var
  FormMain: TFormMain;

implementation

{$R *.frm}

{ TFormMain }

procedure TFormMain.Button1Click(Sender: TObject);
begin
  tthread.CreateAnonymousThread(procedure
  var
    i:      integer;
    webbot: twebbot;
  begin
    formMain.log('初始化WebBot');
    webbot := twebbot.Create(formMain, '127.0.0.1', 12588, 'WebDriver.exe', 'edge');
    try
      for i := 0 to 10 do
      begin
        if webbot.IsConnected then
        begin
          break;
        end;
        sleep(1000);
      end;
      if (webbot.IsConnected) then
      begin
        formMain.log('初始化WebBot成功，准备转到百度');
        webbot.gotoUrl('https://www.baidu.com');
        sleep(1000);
         formMain.log('输入搜索内容');
        webbot.sendKeys('//*[@id="kw"]', '你好黑魔');
        sleep(1000);
         formMain.log('点击搜素');
        webbot.clickElement('//*[@id="su"]');
        formMain.log('等待5秒');
        sleep(5000);

      end
      else
      begin
        formMain.log('初始化WebBot失败');
      end;

      sleep(1000);
      formMain.log('关闭浏览器');
    finally
      webbot.Free;
    end;

  end).start;
end;

procedure TFormMain.Button2Click(Sender: TObject);
begin
  tthread.CreateAnonymousThread(procedure
  var
    i:      integer;
    android: TAndroidBot;
  begin
    formMain.log('初始化AndroidBot');
    android := TAndroidBot.Create;
    try
      for i := 0 to 10 do
      begin
        if android.IsConnected then
        begin
          break;
        end;
        sleep(1000);
      end;
      if (android.IsConnected) then
      begin
        formMain.log('AndroidBot连接成功');
        android.startApp('Aibote');
        sleep(1000);

        formMain.log('等待5秒');
        sleep(5000);

      end
      else
      begin
        formMain.log('初始化AndroidBot失败');
      end;

      sleep(1000);

    finally
      android.Free;
    end;

  end).start;
end;

procedure TFormMain.log(const msg: string);
var
  Sta, len: integer;
  s: string;
begin

  try
  try

    if Length(msg) = 0 then
    begin
      Exit;
    end;



    if GetCurrentThreadId <> MainThreadID then
    begin
      tthread.Synchronize(nil, procedure
      begin
        log(msg);
      end);

    end
    else
    begin
      s := FormatDateTime('[HH:mm:ss]', Now);

      s := s + ' - ' + msg;
      if memo1.Lines.Count > 3000 then
        memo1.Lines.Clear;

      memo1.Lines.Add(s);

    end;

  except

  end;
  finally
  end;

end;

end.
